package com.cby.web.controller;

import com.cby.web.bean.Person;
import com.cby.web.bean.Student;
import com.cby.web.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/student")
public class StudentController {

    @Autowired
    StudentService studentService;

    @RequestMapping(value = "/toLogin", method = RequestMethod.GET)
    public String toLogin() {
        return "/login";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(Person person) {
        if (10025 == person.getPid() && "123".equals(person.getPwd())) {
            return "redirect:queryAll";
        } else {
            return "/login";
        }
    }

    @RequestMapping(value = "/queryAll", method = RequestMethod.GET)
    public ModelAndView queryAll() {
        ModelAndView mav = new ModelAndView("show");
        List<Person> list = new ArrayList<Person>();
        list.add(new Person(10025, "tom", "123"));
        list.add(new Person(10026, "jakson", "123"));
        list.add(new Person(10027, "nikly", "123"));
        mav.addObject("list", list);
        return mav;
    }

    @RequestMapping("/ajax")
    @ResponseBody
    public String ajax(Person person) {
        try{
            System.out.println(person.toString());
            if(studentService != null) {
                Student student = studentService.getStudentByName("jason");
                if(student != null) {
                    System.out.println(student.toString());
                }
            }
            System.out.println(person.getPid() + person.getPwd());
            if (123 == person.getPid() && "123".equals(person.getPwd())) {
                System.out.println("true");
                return "1";
            } else {
                System.out.println("false");
                return "0";
            }
        }catch (Exception e) {
            System.out.println(e.toString());
        }
        return "0";
    }

    @RequestMapping(value = "/ajax2")
    @ResponseBody
    public String ajax2(String loginData) {
        System.out.println(loginData);
        if (loginData != null && !loginData.isEmpty()) {
            System.out.println("true");
            return "1";
        } else {
            System.out.println("false");
            return "0";

        }

    }
}
